package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/counter")
public class BlogCountServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String blogId = req.getParameter("blogId");
        System.out.println(blogId);
        BlogDao blogDao = new BlogDao();
        if(blogId == null){
            HttpSession session = req.getSession(false);
            User user = (User) session.getAttribute("user");
            int userId = user.getUserId();
            user.setCounter(blogDao.countBlog(userId));
            String respJson = objectMapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
        }else{
            Blog blog = blogDao.selectById(Integer.parseInt(blogId));
            if (blog == null) {
                System.out.println("当前 blogId =" + blogId + "对应的博客不存在！");
            }
            int userId = blog.getUserId();
            UserDao userDao = new UserDao();
            User user = userDao.selectById(userId);
            user.setCounter(blogDao.countBlog(userId));
            String respJson = objectMapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
        }
    }
}
